package crawler

import static org.springframework.http.HttpStatus.*
import grails.transaction.Transactional
import java.text.SimpleDateFormat
import org.jsoup.Jsoup

@Transactional(readOnly = true)
class StocksController {

    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]

    @Transactional
    def stocksInitiate()
    {
        // for (def i=2000;i<3000;i++)
        // {
        //     def code 

        //     if(i<10){code="00000"+i.toString()}
        //     else if (i<100) {code="0000"+i.toString()}
        //     else if (i<1000) {code="000"+i.toString()}
        //     else {code="00"+i.toString()}
            
        //     stocksQuery(code)             

        //     System.sleep(1000 * 30)
        // }
        stocksQuery("001696")
        stocksQuery("001896")
        stocksQuery("001979")
        
        
        redirect action:"index", method:"GET"
    }

    @Transactional
    def stocksQuery(String code)
    {
        println code
        def result = []
        def url = "http://quotes.money.163.com/f10/gdfx_"+code+".html#01d02"
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd")
        try 
        {
            def doc = Jsoup.connect(url).timeout(5000).get()
        
            def name = doc.select(".stock_info > table > tbody > tr > td > h1 > a").text()
            def equity = doc.select(".col_r_01 > table > tbody > tr ")                 
            result[0] = name
            result[1] = equity[0].select("> td")[1].text().toDouble()
            result[2] = equity[1].select("> td")[1].text().toDouble()       
            Stocks tempStock = new Stocks()
            tempStock = Stocks.findByCode(code)

            if(!tempStock)
            {
                Stocks stock = new Stocks()            
                stock.code = code
                stock.name = result[0]
                stock.totalEquity = result[1]
                stock.liquidEquity = result[2]
                stock.modifiedDate = new Date()
                stock.save flush:true, insert:true
            }
            else
            {              
                tempStock.totalEquity = result[1]
                tempStock.liquidEquity = result[2]
                tempStock.modifiedDate = new Date()
                tempStock.save flush:true
            }        

                
        }
        catch (Exception e)
        {
            System.out.println("连接网址不对")
        } 
        
        
    }

    def index(Integer max) {
        params.max = Math.min(max ?: 10, 100)
        respond Stocks.list(params), model:[stocksCount: Stocks.count()]
    }

    def show(Stocks stocks) {
        respond stocks
    }

    def create() {
        respond new Stocks(params)
    }

    @Transactional
    def save(Stocks stocks) {
        if (stocks == null) {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (stocks.hasErrors()) {
            transactionStatus.setRollbackOnly()
            respond stocks.errors, view:'create'
            return
        }

        stocks.save flush:true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.created.message', args: [message(code: 'stocks.label', default: 'Stocks'), stocks.id])
                redirect stocks
            }
            '*' { respond stocks, [status: CREATED] }
        }
    }

    def edit(Stocks stocks) {
        respond stocks
    }

    @Transactional
    def update(Stocks stocks) {
        if (stocks == null) {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (stocks.hasErrors()) {
            transactionStatus.setRollbackOnly()
            respond stocks.errors, view:'edit'
            return
        }

        stocks.save flush:true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.updated.message', args: [message(code: 'stocks.label', default: 'Stocks'), stocks.id])
                redirect stocks
            }
            '*'{ respond stocks, [status: OK] }
        }
    }

    @Transactional
    def delete(Stocks stocks) {

        if (stocks == null) {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        stocks.delete flush:true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.deleted.message', args: [message(code: 'stocks.label', default: 'Stocks'), stocks.id])
                redirect action:"index", method:"GET"
            }
            '*'{ render status: NO_CONTENT }
        }
    }

    protected void notFound() {
        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.not.found.message', args: [message(code: 'stocks.label', default: 'Stocks'), params.id])
                redirect action: "index", method: "GET"
            }
            '*'{ render status: NOT_FOUND }
        }
    }
}
